package web.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.Enumeration;

@WebServlet("/fileUpload")
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
    // 上传文件存储目录
//    private static final String UPLOAD_DIRECTORY = "/www/wwwroot/java_fujie_bid/TTMS/ttms_upload";
    private static final String UPLOAD_DIRECTORY = "/home/fujie/ttms_upload";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Enumeration<String> heads = request.getHeaderNames();

        while (heads.hasMoreElements()) {
            String header = heads.nextElement();
            System.out.println(header + "=" + request.getHeader(header));
        }
        Part part = request.getPart("file");
        Collection<String> headerNames = part.getHeaderNames();

        for (String header : headerNames) {
            System.out.println(header + "=" + part.getHeader(header));
        }
        InputStream is = part.getInputStream();
        String filename = new String(getFilename(part).getBytes(), "UTF-8");
        File file = new File(UPLOAD_DIRECTORY);
        if (!file.exists() || !file.isDirectory()) {
            file.mkdir();
        }

        FileOutputStream fos = new FileOutputStream(new File(file + File.separator + filename));
        byte[] buf = new byte[1024];
        while (is.read(buf) != -1) {
            fos.write(buf);
        }
        fos.flush();
        fos.close();
        is.close();
    }

    public String getFilename(Part part) {
        String contentDispositionHeader = part.getHeader("content-disposition");
        String[] elements = contentDispositionHeader.split(";");
        for (String element : elements) {
            if (element.trim().startsWith("filename")) {
                return element.substring(element.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

}
